package com.stedu.mall.userservice.controller;

import com.stedu.mall.common.bean.Collect;
import com.stedu.mall.common.bean.RespBean;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.CollectService;
import com.stedu.mall.common.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/collect")
public class CollectController {
    @Autowired
    private CollectService collectService;
    @PostMapping("/{goodsId}")
    //添加 -- 收藏
    public RespBean insert(@PathVariable("goodsId")Integer goodsId, @RequestHeader("token") String token) throws SteduException {
        Map<String,Object>map = JwtUtil.parseJwtToMap(token);
        Integer id = (Integer) map.get("id");
        Collect collect = new Collect();
        collect.setUserId(id);
        collect.setGoodsId(goodsId);
        //添加
        collectService.insert(collect);
        return RespBean.ok("收藏成功");
    }
    //删除 --取消收藏
    @DeleteMapping("/{id}")
    public RespBean delete(@PathVariable("id") Integer id, @RequestHeader("token") String token) throws SteduException {
        Map<String,Object>map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        collectService.delete(id,userId);
        return RespBean.ok("取消收藏成功");
    }
    //根据商品id和用户id查询收藏
    @GetMapping("/{goodsId}")
    public RespBean selectByGoodsIDAndUserId(@PathVariable("goodsId") Integer goodsId, @RequestHeader("token") String token) {
        Map<String,Object>map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer) map.get("id");
        Collect collect = collectService.selectByGoodsIDAndUserId(userId,goodsId);
        return RespBean.ok("查询成功", collect);


    }
    //根据用户id查询收藏列表
    @GetMapping
    private RespBean selectByPage(Integer pageNum, Integer pageSize, @RequestHeader("token") String token) {
        //解析token获取用户id
        Map<String, Object> map = JwtUtil.parseJwtToMap(token);
        Integer userId = (Integer)map.get("id");
        return RespBean.ok("查询成功", collectService.selectByPage(userId, pageNum, pageSize));
    }

}
